#include "session.h"

void Session::Start(){
    memset(data_,0,max_length);
    socket_.async_read_some(boost::asio::buffer(data_,max_length),
    std::bind(&Session::ReadHandle,this,std::placeholders::_1,std::placeholders::_2,shared_from_this()));
}

void Session::ReadHandle(const boost::system::error_code error,std::size_t bytes_transferred,
std::shared_ptr<Session>self_shared_)
{
    std::cout << "session->use_count:" <<self_shared_.use_count() << std::endl;
    if (!error)
    {
        std::cout << "receive data:" << data_ << std::endl;
        //读完之后立马挂起读函数，即随时读
        socket_.async_read_some(boost::asio::buffer(data_,max_length),
        std::bind(&Session::ReadHandle,this,std::placeholders::_1,std::placeholders::_2,self_shared_));

        //挂起读函数之后再次写，如果出现客户端临时断开，要考虑双重delete的问题
        socket_.async_write_some(boost::asio::buffer(data_,bytes_transferred),
        std::bind(&Session::WriteHandle,this,std::placeholders::_1,std::placeholders::_2,self_shared_));
    }
    else
    {
        std::cout << "read error\n" << "error.value:" <<error.value() << "error.message:" << error.message() <<std::endl;
        // ClearSelf(this->uuid_);
        server_->ClearSession(uuid_);
    }
    
}

void Session::WriteHandle(const boost::system::error_code error,std::size_t bytes_transferred,
std::shared_ptr<Session>self_shared_)
{
    std::cout << "session->use_count:" <<self_shared_.use_count() << std::endl;
    if (!error)
    {
        memset(data_,0,max_length);
        socket_.async_read_some(boost::asio::buffer(data_,max_length),
        std::bind(&Session::ReadHandle,this,std::placeholders::_1,std::placeholders::_2,self_shared_));
    }
    else
    {
        std::cout << "write error\n" << "error.value:" <<error.value() << "error.message:" << error.message() <<std::endl;
        // ClearSelf(this->uuid_);
        server_->ClearSession(uuid_);
    }
    
}
